#!/bin/bash

set -e

ENUM_OS_LINUX=linux
ENUM_OS_MACOS=darwin
ENUM_ARCH_AMD64=amd64
ENUM_ARCH_ARM64=arm64

# 打印help
print_help() {
    echo "Usage: $(basename $0) [-h --help] [-v --version]"
    echo "  -h, --help                  显示帮助信息"
    echo "  -v, --version <版本号>      指定版本"
}

# 获取操作系统
if [[ "$(uname)" == "Darwin" ]]; then
    OS=$ENUM_OS_MACOS
elif [[ "$(uname)" == "Linux" ]]; then
    OS=$ENUM_OS_LINUX
else
    echo "未知操作系统: $(uname)"
    exit 1
fi

# 获取架构
if [[ $(uname -m) == "aarch64" || $(uname -m) == "arm64" ]]; then
    ARCH=$ENUM_ARCH_ARM64
elif [[ $(uname -m) == "x86_64" ]]; then
    ARCH=$ENUM_ARCH_AMD64
else
    echo "未知架构：$(uname -m)"
    exit 1
fi

# 解析参数
while [[ "$#" -gt 0 ]]; do
  case $1 in
    -h|--help)
        print_help
        exit 0
        ;;
    -v|--version)
        if [[ -n "$2" ]]; then
          VERSION=$2
          shift
        else
          echo "错误: --version 需要一个参数"
          exit 1
        fi
        ;;
    *)
        echo "未知选项: $1"
        print_help
        ;;
  esac
  shift
done

# 安装依赖
apt update -y 
apt install -y wget curl
apt clean && rm -rf /var/lib/apt/lists/* /var/tmp/*

if [ -z $VERSION ]; then
    LATEST_VERSION=$(curl -s https://go.dev/VERSION?m=text | grep go)
    echo "未通过--version选项指定版本，默认使用最新稳定版本[${LATEST_VERSION}]"
    VERSION=${LATEST_VERSION}
fi

echo "========================"
echo "    系统:${OS}"
echo "    架构:${ARCH}"
echo "    版本:${VERSION}"
echo "========================"

install_tgz() {
    url=$1
    file=/tmp/$(basename ${url})

    # 下载
    echo "开始下载 ${url} 到 ${file}"
    if [[ -e ${file} ]]; then
        echo "${file} 已存在，跳过下载"
    else
        echo "开始下载, url=${url}，路径=${file}"
        wget ${url} -O ${file}
    fi

    # 解压
    dir=/usr/local/$(tar -ztf ${file} | head -1 | cut -d'/' -f1)
    echo "开始解压到 ${dir}"
    if [[ -d ${dir} ]]; then
        echo "${dir} 已存在，跳过解压"
    else
        echo "开始解压, dir=${dir}"
        tar -zxvf ${file} -C /usr/local
    fi

    # PATH
    bindir=${dir}/bin
    echo "开始设置PATH ${bindir}"
    if grep -q "${bindir}" ~/.bashrc; then
        echo "${bindir} 已存在于 PATH, 跳过PATH设置"
    else
        echo "在 ~/.bashrc 设置 ${bindir} PATH"
        echo "export PATH=\$PATH:${bindir}" >> ~/.bashrc
    fi
    export PATH=$PATH:${bindir}
}

install_tgz https://dl.google.com/go/${VERSION}.${OS}-${ARCH}.tar.gz

# 设置环境变量
FLAG="GO ENV"
if grep -q "${FLAG}" ~/.bashrc; then
    echo "~/.bashrc 已设置环境变量, 跳过设置"
else
    cat >> ~/.bashrc << EOF

# ${FLAG}
export GOROOT=/usr/local/go
export GOPATH=~/go
export PATH=\$PATH:\$GOROOT/bin
export PATH=\$PATH:\$GOPATH/bin
export GOSUMDB=off
export GOPROXY=https://goproxy.cn,direct
EOF
fi

# 验证安装
. ~/.bashrc
go version

# 安装vim-go所需的go tools（可选）
install_go_tools=${INSTALL_GO_TOOLS:-true}
if [ "$install_go_tools" = "true" ]; then
    echo "开始安装vim-go所需的go tools..."
    
    # 设置代理加速
    export GOPROXY=https://goproxy.cn,direct
    export GOSUMDB=off
    
    # 安装常用工具
    go install golang.org/x/tools/gopls@latest
    go install github.com/go-delve/delve/cmd/dlv@latest
    go install github.com/fatih/gomodifytags@latest
    go install github.com/josharian/impl@latest
    go install github.com/cweill/gotests/gotests@latest
    go install honnef.co/go/tools/cmd/staticcheck@latest
    go install github.com/davidrjenni/reftools/cmd/fillstruct@latest
    go install golang.org/x/tools/cmd/goimports@latest
    
    echo "go tools 安装成功！"
else
    echo "跳过go tools安装（设置 INSTALL_GO_TOOLS=true 来安装）"
fi

echo "go ${OS}-${ARCH}-${VERSION} 安装成功！"
